#include "thttpd.h"
#include "custom_handle.h"
#include "common.h"
#include "shmem.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define KB 1024
#define HTML_SIZE (64 * KB)

// 统一的HTTP响应发送函数
static void send_http_response(int sock, const char *content, const char *content_type) {
    char header[512];
    snprintf(header, sizeof(header), 
        "HTTP/1.1 200 OK\r\n"
        "Content-Type: %s\r\n"
        "Content-Length: %zu\r\n"
        "Connection: close\r\n"
        "\r\n",
        content_type, strlen(content));
    
    send(sock, header, strlen(header), 0);
    send(sock, content, strlen(content), 0);
}

// 发送JSON格式的响应
static void send_json_response(int sock, const char *json) {
    send_http_response(sock, json, "application/json");
}

// 用户登录处理
static int handle_login(int sock, const char *input) {
    char reply_buf[HTML_SIZE] = {0};
    char *uname = strstr(input, "username=");
    char *p = strstr(input, "password");
    
    if (!uname || !p) {
        send_json_response(sock, "{\"error\":\"Missing username or password\"}");
        return -1;
    }

    uname += strlen("username=");
    *(p - 1) = '\0';
    printf("username = %s\n", uname);
    
    char *passwd = p + strlen("password=");
    printf("passwd = %s\n", passwd);

    // 登录验证逻辑
    if (strcmp(uname, "hello") == 0 && strcmp(passwd, "123456") == 0) {
        sprintf(reply_buf, "{\"status\":\"success\",\"redirect\":\"/world.html\"}");
    } else {
        sprintf(reply_buf, "{\"status\":\"failed\",\"error\":\"Invalid username or password\"}");
    }

    send_json_response(sock, reply_buf);
    return 0;
}

// 从共享内存读取数据
static int handle_shm_read(int sock, const char *input) {
    // 初始化共享内存
    struct shm_param para;
    if (shm_init(&para, SHM_NAME, SHM_SIZE) < 0) {
        send_json_response(sock, "{\"error\":\"Shared memory init failed\"}");
        return -1;
    }

    void *shm_addr = shm_getaddr(&para);
    if (!shm_addr) {
        send_json_response(sock, "{\"error\":\"Failed to get shared memory address\"}");
        return -1;
    }

    int *total = (int *)shm_addr;
    struct std_node *node_arr = (struct std_node *)(total + 1);

    // 解析key参数
    char *key_str = strstr(input, "key=");
    if (!key_str) {
        send_json_response(sock, "{\"error\":\"Missing key parameter\"}");
        return -1;
    }

    key_str += strlen("key=");
    int key = atoi(key_str);

    // 搜索节点
    char response[256];
    printf("开始搜索节点\n");
    printf("节点数 = %d\n", *total);
    for (int i = 0; i < *total && i < MAX_NODES; i++) {
        if (node_arr[i].key == key) {
            if (node_arr[i].type == 1) {
                snprintf(response, sizeof(response), "{\"key\":%d,\"type\":\"bool\",\"value\":%d}", 
                         key, node_arr[i].new_val.b_val);
            } else if (node_arr[i].type == 2) {
                snprintf(response, sizeof(response), "{\"key\":%d,\"type\":\"int\",\"value\":%d}", 
                         key, node_arr[i].new_val.i_val);
            } else if (node_arr[i].type == 3) {
                snprintf(response, sizeof(response), "{\"key\":%d,\"type\":\"float\",\"value\":%.2f}", 
                         key, node_arr[i].new_val.f_val);
            } else {
                snprintf(response, sizeof(response), "{\"key\":%d,\"error\":\"Unknown type\"}", key);
            }
            
            
            send_json_response(sock, response);
            return 0;
        }
        printf("node_arr[%d].key = %d\n", i, node_arr[i].key);
    }
    printf("搜索节点完成\n");

    send_json_response(sock, "{\"error\":\"Key not found\"}");
    return -1;
}

// 向消息队列写入控制命令
static int handle_msg_write(int sock, const char *input) {
    char *key_str = strstr(input, "key=");
    char *val_str = strstr(input, "value=");
    char *type_str = strstr(input, "type=");

    if (!key_str || !val_str || !type_str) {
        send_json_response(sock, "{\"error\":\"Missing parameters\"}");
        return -1;
    }

    key_str += strlen("key=");
    val_str += strlen("value=");
    type_str += strlen("type=");

    // 解析参数
    int key = atoi(key_str);
    int type = atoi(type_str);
    union val_t val;

    if (type == 1) { // bool
        val.b_val = atoi(val_str) ? 1 : 0;
    } else if (type == 2) { // int
        val.i_val = atoi(val_str);
    } else if (type == 3) { // float
        val.f_val = atof(val_str);
    } else {
        send_json_response(sock, "{\"error\":\"Invalid type\"}");
        return -1;
    }

    // 构造消息
    struct control_msg msg;
    msg.mtype = (key >= 100) ? MSG_TYPE_CONTROL : MSG_TYPE_CONTROL_2;
    msg.key = key;
    msg.value = val;
    msg.type = type;

    // 发送消息
    if (msg_queue_send("device_control", &msg, sizeof(msg), 0) < 0) {
        send_json_response(sock, "{\"error\":\"Failed to send control message\"}");
        return -1;
    }

    send_json_response(sock, "{\"status\":\"success\"}");
    return 0;
}

// 主请求处理函数
int parse_and_process(int sock, const char *query_string, const char *input) {
    printf("Processing request: %s\n", input);

    // 处理登录请求
    if (strstr(input, "username=") && strstr(input, "password=")) {
        return handle_login(sock, input);
    }
    // 处理Modbus读取请求
    else if (strstr(input, "modbus_read=")) {
        return handle_shm_read(sock, input + strlen("modbus_read="));
    }
    // 处理Modbus写入请求
    else if (strstr(input, "modbus_write=")) {
        return handle_msg_write(sock, input + strlen("modbus_write="));
    }
    // 处理共享内存读取请求
    else if (strstr(input, "shm_read=")) {
        return handle_shm_read(sock, input + strlen("shm_read="));
    }
    // 处理控制命令写入请求
    else if (strstr(input, "control_write=")) {
        return handle_msg_write(sock, input + strlen("control_write="));
    }
    // 默认响应
    else {
        send_json_response(sock, "{\"error\":\"Unsupported request type\"}");
    }
    
    return 0;
}